package openadmin.util;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class ControlNif {
	
	private static String letters = "TRWAGMYFPDXBNJZSQVHLCKE";
	
	public static boolean isNifNie(String nif){
		 
		if (nif.toUpperCase().startsWith("X")||nif.toUpperCase().startsWith("Y")||nif.toUpperCase().startsWith("Z"))
			nif = nif.substring(1).toUpperCase();
		 
		Pattern nifPattern = Pattern.compile("(\\d{1,8})([" + letters + "])");
		Matcher m = nifPattern.matcher(nif);
		
		if(m.matches()){	
			
			int result = Integer.parseInt(m.group(1)) % 23;
			String letter = letters.substring(result,result+1);
		 
			if (letter.equalsIgnoreCase(m.group(2))){
				
				return true;
				
			} else {
				
				return false;
			}
			
		} else
			
			return false;
	}

	public static String letterNifNie(String dni){
		
		String result = "Error dni";
		
		if (dni.toUpperCase().startsWith("X")||dni.toUpperCase().startsWith("Y")||dni.toUpperCase().startsWith("Z"))
			dni = dni.substring(1).toUpperCase();
		
		Pattern nifPattern = Pattern.compile("(\\d{1,8})");
		Matcher m = nifPattern.matcher(dni);
		
		if(m.matches()){	
			
			int res = Integer.parseInt(m.group(1)) % 23;
			result = letters.substring(res,res+1);
			
		}
		
		return result;
	}
	
	
	public static void main(String[] args) {
		
		isNifNie("X3911750W");
		System.out.println("La lletra es. "+letterNifNie("X3911750"));
	}
}
